package com.changgou.gateway.filter;

import com.changgou.gateway.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局过滤器，过滤用户的请求。需要登陆上才可以访问别的微服务
 *      如果是登录就放行
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    //令牌头名字
    private static final String AUTHORIZE_TOKEN = "Authorization";

    private static final String LOGIN_URL="http://localhost:9001/oauth/login";

    /**
     * 全局过滤器
     */
    //判断权限的的逻辑代码
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象
        ServerHttpRequest request = exchange.getRequest();

        //2.获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //3.判断当前的请求路径 如果是以/api/user/login的路径开头 放行即可
        String path = request.getURI().getPath();

        if(path.startsWith("/api/oauth/login")){
            //放行
            return chain.filter(exchange);
        }
        //4.从请求头中获取令牌  如果获取不到
        String token = request.getHeaders().getFirst(AUTHORIZE_TOKEN);
        if(StringUtils.isEmpty(token)){
            //5.再从请求参数中获取令牌  如果获取不到
            token = request.getQueryParams().getFirst(AUTHORIZE_TOKEN);
        }
        if(StringUtils.isEmpty(token)){
            //6.再从cookie中获取令牌 如果获取不到
            HttpCookie cookie = request.getCookies().getFirst(AUTHORIZE_TOKEN);
            if(cookie!=null){
                token= cookie.getValue();
            }
        }
        if(StringUtils.isEmpty(token)){
            //没有令牌  说明无权限 直接返回登录界面
            response.getHeaders().set("Location",LOGIN_URL+"?FROM="+request.getURI().toString());
            response.setStatusCode(HttpStatus.SEE_OTHER);
            return response.setComplete();//请求完成

           /* //7.如果令牌为空，返回；结束请求
            //设置响应的状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();*/
        }



        //8.解析令牌，如果解析失败 返回
        String claims=null;
        try {
//            Claims claims = JwtUtil.parseJWT(token);
            //将令牌数据添加到请求头中
//            request.mutate().header(AUTHORIZE_TOKEN,"Bearer "+token);

            //如果获取到的token不为空，则直接进行解析
            Jwt jwt = JwtHelper.decodeAndVerify(token, new RsaVerifier(JwtUtil.publickey));
            claims= jwt.getClaims();
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        System.out.println("Clams："+claims);
        //实现一个判断  是否是前台用户类型的登录判断
        //获取数据，封装到头里
        request.mutate().header(AUTHORIZE_TOKEN, claims);

        //9.放行
        return chain.filter(exchange);
    }


    /***
     * 过滤器执行顺序
     */
    @Override
    public int getOrder() {
        return 0;
    }
}